package com.googlecode.stemwijzer.rebind;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.ext.typeinfo.JMethod;
import com.google.gwt.core.ext.typeinfo.JParameter;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;

/**
 * The Class EntityGenerator.
 * 
 * @author j.brosens
 */
public class EntityGenerator extends BaseGenerator {

	@Override
	protected void onCompose(final ClassSourceFileComposerFactory composer) {
		composer.addImplementedInterface(this.generatedType
				.getQualifiedSourceName());
	}

	@Override
	protected void onGenerate() {
		generateGettersSetters();
	}

	private void generateGettersSetters() {
		List<String> propertyNames = new ArrayList<String>();

		for (JMethod method : this.generatedType.getMethods()) {
			String methodName = method.getName();

			if (methodName.startsWith("get")) {
				String type = method.getReturnType().getQualifiedSourceName();
				String propertyName = getPropertyName(method);
				propertyNames.add(propertyName);

				writeProperty(propertyName, type);
				writeOverriddenPropertyMethodHeader(method);

				srcWriter.println("return this." + propertyName + ";");

				writeCloseMethod();
			} else if (method.getName().startsWith("set")) {
				if (propertyNames.contains(getPropertyName(method))) {
					JParameter setterParam = method.getParameters()[0];

					writeOverriddenPropertyMethodHeader(method);

					srcWriter.println("this." + setterParam.getName() + " = "
							+ setterParam.getName() + ";");

					writeCloseMethod();
				}
			}
		}
	}
}
